<template>
  <div class="qr-wrapper" :style="{ width: size + 'px', height: size + 'px', position: 'relative' }">
    <canvas ref="canvasEl" style="width: 100%;height: 100%"></canvas>
    <!-- 中心Logo -->
    <img
        v-if="logoSrc"
        :src="logoSrc"
        alt="logo"
        :style="{
        position: 'absolute',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        width: logoSize + 'px',
        height: logoSize + 'px',
        background: '#fff',
        padding: logoPadding + 'px',
        borderRadius: logoRound ? '12%' : '0'
      }"
    />
  </div>
</template>

<script>
import {ref, onMounted, watch, computed, nextTick} from "vue";
import QRCode from "qrcode";

export default {
  name: "QRCode",
  props: {
    value: {type: String, required: true},
    level: {type: String, default: "M"}, // 容错等级 L/M/Q/H
    margin: {type: Number, default: 2},
    darkColor: {type: String, default: "#000000"},
    lightColor: {type: String, default: "#ffffff"},
    logoSrc: {type: String, default: null},
    logoScale: {type: Number, default: 0.18}, // logo 占比
    logoPadding: {type: Number, default: 4},
    logoRound: {type: Boolean, default: true},
  },
  setup(props) {
    const canvasEl = ref(null);

    const logoSize = computed(() => Math.round(props.size * props.logoScale));

    async function draw() {
      if (!canvasEl.value) return;
      const options = {
        errorCorrectionLevel: props.level,
        margin: props.margin,
        color: {
          dark: props.darkColor,
          light: props.lightColor,
        },
      };
      await QRCode.toCanvas(canvasEl.value, props.value || "", options);
    }

    async function toDataURL(type = "image/png", quality = 0.92) {
      if (!canvasEl.value) return "";
      return canvasEl.value.toDataURL(type, quality);
    }

    async function download(filename = "qrcode.png") {
      const url = await toDataURL();
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      a.click();
    }

    onMounted(async () => {
      await nextTick();
      draw();
    });

    watch(
        () => [
          props.value,
          props.level,
          props.margin,
          props.darkColor,
          props.lightColor,
        ],
        () => draw()
    );

    return {
      canvasEl,
      logoSize,
      draw,
      toDataURL,
      download,
    };
  },
};
</script>
